//
//  QPJHNetworkManager.m
//  qipajuhe
//
//  Created by 7pagame on 2018/11/6.
//  Copyright © 2018年 Vanney. All rights reserved.
//

#import "SQPJHNetworkManager.h"
#import "QPSaccountStore.h"
#import "UIView+Toast.h"
#import "QPJHFunDataFormat.h"
#import "QPConstHeader.h"
#import "libQPJHLightChannel.h"
#import <CommonCrypto/CommonCryptor.h>
#import <Security/Security.h>
#import "GTMBase64.h"
#import "YZYDeviceInfoUUID.h"

#define gkey            @"c5fcdac4fc05bb8bbe244862cb8e0b05"

#define gIv             @"20220409"

NSString *const SResponseErrorKey = @"com.alamofire.serialization.response.error.response";
NSInteger const SInterval = 3;

@interface SQPJHNetworkManager()

@end

@implementation SQPJHNetworkManager
//原生GET网络请求
+ (void)getWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure {
    //完整URL
    NSString *urlString = [NSString string];
    if (params) {
        //参数拼接url
        NSString *paramStr = [self dealWithParam:params];
        urlString = [NSString stringWithFormat:@"%@?%@",url,paramStr];
    }else{
        urlString = url;
    }

    //对URL中的中文进行转码
    NSString *pathStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:pathStr]];
    
    request.timeoutInterval = SInterval;
    
    NSString *gameId = [QPJHFunDataFormat QPJHGetGameID];
    NSString *sdkVersion = QPSDKVERSION;
    NSString *packageName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *osType = @"2";
    NSString *deviceName = [QPJHFunDataFormat getCurrentDeviceModel];
    NSString *platformId = [libQPJHLightChannel sharedInstance].platformId;
    NSString *devicesInfo = [YZYDeviceInfoUUID createDeviceInfoUUID];
    
    [request setValue:gameId forHTTPHeaderField:@"gameId"];
    [request setValue:platformId forHTTPHeaderField:@"platformId"];
    [request setValue:packageName forHTTPHeaderField:@"packageName"];
    [request setValue:osType forHTTPHeaderField:@"osType"];
    [request setValue:deviceName forHTTPHeaderField:@"deviceName"];
    [request setValue:sdkVersion forHTTPHeaderField:@"sdkVersion"];
    [request setValue:devicesInfo forHTTPHeaderField:@"devicesInfo"];

    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
               
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                success(dict);
                
            }else{
                NSHTTPURLResponse *httpResponse = error.userInfo[SResponseErrorKey];
                
                if (httpResponse.statusCode != 0) {
                    
                    NSString *ResponseStr = [self showErrorInfoWithStatusCode:httpResponse.statusCode];
                    failure(ResponseStr);
                    
                } else {
                    NSString *ErrorCode = [self showErrorInfoWithStatusCode:error.code];
                    failure(ErrorCode);
                }
            }
            
        });
    }];
    
    [task resume];
}

//原生POST请求
+ (void)PostWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    
    //把字典中的参数进行拼接
    NSString *body = [self dealWithParam:params];
    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    //设置请求体
    [request setHTTPBody:bodyData];
    //设置本次请求的数据请求格式
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    // 设置本次请求请求体的长度(因为服务器会根据你这个设定的长度去解析你的请求体中的参数内容)
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"];
    //设置请求最长时间
    request.timeoutInterval = SInterval;
    
    NSString *gameId = [QPJHFunDataFormat QPJHGetGameID];
    NSString *sdkVersion = QPSDKVERSION;
    NSString *packageName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *osType = @"2";
    NSString *deviceName = [QPJHFunDataFormat getCurrentDeviceModel];
    NSString *platformId = [libQPJHLightChannel sharedInstance].platformId;
    NSString *devicesInfo = [YZYDeviceInfoUUID createDeviceInfoUUID];

    [request setValue:gameId forHTTPHeaderField:@"gameId"];
    [request setValue:platformId forHTTPHeaderField:@"platformId"];
    [request setValue:packageName forHTTPHeaderField:@"packageName"];
    [request setValue:osType forHTTPHeaderField:@"osType"];
    [request setValue:deviceName forHTTPHeaderField:@"deviceName"];
    [request setValue:sdkVersion forHTTPHeaderField:@"sdkVersion"];
    [request setValue:devicesInfo forHTTPHeaderField:@"devicesInfo"];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            //利用iOS自带原生JSON解析data数据 保存为Dictionary
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -success- %@", url, request.allHTTPHeaderFields, params, dict);

            NSString *msg = [NSString stringWithFormat:@"%@", dict[@"msg"]];
            NSString *code = [NSString stringWithFormat:@"%@", dict[@"code"]];
            if ([code isEqualToString:@"400"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:msg];
                });
            }
             
            success(dict);
            
        }else{
            NSHTTPURLResponse *httpResponse = error.userInfo[SResponseErrorKey];
            
            if (httpResponse.statusCode != 0) {
                
                NSString *ResponseStr = [self showErrorInfoWithStatusCode:httpResponse.statusCode];
                NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -error- %@", url, request.allHTTPHeaderFields, params, ResponseStr);

                failure(ResponseStr);
                
            } else {
                NSString *ErrorCode = [self showErrorInfoWithStatusCode:error.code];
                NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -error- %@", url, request.allHTTPHeaderFields, params, ErrorCode);

                failure(ErrorCode);
            }
        }
    }];
    [task resume];
}

//原生POST请求 加密方式
+ (void)cryptPostWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    if (!params) params = @{};
    NSError *paramsError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&paramsError];
    NSString *paramsStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //把字典中的参数进行拼接
    NSString *body = [self doEncryptStr:paramsStr];
    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    //设置请求体
    [request setHTTPBody:bodyData];
    //设置本次请求的数据请求格式
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置本次请求请求体的长度(因为服务器会根据你这个设定的长度去解析你的请求体中的参数内容)
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"];
    //设置请求最长时间
    request.timeoutInterval = SInterval;
    
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            //利用iOS自带原生JSON解析data数据 保存为Dictionary
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -success- %@", url, request.allHTTPHeaderFields, params, dict);

            NSString *msg = [NSString stringWithFormat:@"%@", dict[@"msg"]];
            NSString *code = [NSString stringWithFormat:@"%@", dict[@"code"]];
            if ([code isEqualToString:@"400"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:msg];
                });
            }
             
            success(dict);
            
        }else{
            NSHTTPURLResponse *httpResponse = error.userInfo[SResponseErrorKey];
            
            if (httpResponse.statusCode != 0) {
                
                NSString *ResponseStr = [self showErrorInfoWithStatusCode:httpResponse.statusCode];
                NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -error- %@", url, request.allHTTPHeaderFields, params, ResponseStr);

                failure(ResponseStr);
                
            } else {
                NSString *ErrorCode = [self showErrorInfoWithStatusCode:error.code];
                NSLog(@"-----------POST url-%@\nheaders- %@\nparams- %@ -error- %@", url, request.allHTTPHeaderFields, params, ErrorCode);

                failure(ErrorCode);
            }
        }
    }];
    [task resume];
}


#pragma mark -- 拼接参数
+ (NSString *)dealWithParam:(NSDictionary *)param
{
    NSArray *allkeys = [param allKeys];
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys) {
        NSString *string = [NSString stringWithFormat:@"%@=%@&", key, param[key]];
        [result appendString:string];
    }
    NSString *str = [NSString stringWithFormat:@"%@",[result substringWithRange:NSMakeRange(0, [result length] - 1)]];

    return str;
}

#pragma mark
+ (NSString *)showErrorInfoWithStatusCode:(NSInteger)statusCode{
    
    NSString *message = nil;
    switch (statusCode) {
        case 401: {
            
        }
            break;
            
        case 500: {
            message = @"服务器异常！";
        }
            break;
            
        case -1001: {
            message = @"网络请求超时，请稍后重试！";
        }
            break;
            
        case -1002: {
            message = @"不支持的URL！";
        }
            break;
            
        case -1003: {
            message = @"未能找到指定的服务器！";
        }
            break;
            
        case -1004: {
            message = @"服务器连接失败！";
        }
            break;
            
        case -1005: {
            message = @"连接丢失，请稍后重试！";
        }
            break;
            
        case -1009: {
            message = @"互联网连接似乎是离线！";
        }
            break;
            
        case -1012: {
            message = @"操作无法完成！";
        }
            break;
            
        default: {
            message = @"网络请求发生未知错误，请稍后再试！";
        }
            break;
    }
    return message;
    
}

//加密
+ (NSString *)doEncryptStr:(NSString *)originalStr{
    
    NSData* data = [originalStr dataUsingEncoding:NSUTF8StringEncoding];
    
    size_t plainTextBufferSize = [data length];
    
    const void *vplainText = (const void *)[data bytes];
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [gkey UTF8String];
 
    const void *vinitVec = (const void *) [gIv UTF8String];
    
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithm3DES,
                       kCCOptionPKCS7Padding,
                       vkey,
                       kCCKeySize3DES,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    NSString *result = [GTMBase64 stringByEncodingData:myData];
    return result;
}



@end
